<template>
	<view class="container">
		<!-- 顶部操作栏 -->
		<view class="header-card">
			<view class="header-content">
				<view class="praise-controls">
					<picker mode="selector" :range="subjects" @change="changeSubject">
						<view class="subject-picker">
							<text class="subject-text">{{selectedSubject || '选择学科'}}</text>
							<uni-icons type="arrowdown" size="20" color="#fff"></uni-icons>
						</view>
					</picker>

					<view class="praise-input">
						<input v-model="newPraiseTitle" placeholder="输入表扬主题" class="praise-input-field"
							placeholder-class="placeholder" />
						<button class="add-btn" @click="addPraiseTitle">
							<text>添加</text>
							<uni-icons type="plus" size="16" color="#fff"></uni-icons>
						</button>
					</view>
				</view>

				<!-- 表扬主题标签 -->
				<view class="praise-tags-container">
					<scroll-view scroll-x class="praise-tags-scroll">
						<view class="praise-tags">
							<view v-for="(title, index) in praiseTitles" :key="index" class="praise-tag"
								:class="{active: selectedPraiseTitle === title}" @click="selectPraiseTitle(title)">
								<text>{{title}}</text>
								<view class="remove-icon" @click.stop="removePraiseTitle(index, $event)">
									<uni-icons type="close" size="14" color="currentColor"></uni-icons>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>

		<!-- 已表扬学生标签 -->
		<!-- 修改已表扬学生标签部分 -->
		<view class="praised-tags" v-if="filteredPraisedStudents.length > 0">
			<text class="praised-label">今日已表扬:</text>
			<view class="praised-students">
				<view v-for="student in filteredPraisedStudents" :key="student.studentId" class="praised-tag">
					{{student.studentName}}
				</view>
			</view>
		</view>

		<!-- 学生列表 -->
		<scroll-view class="student-list" scroll-y>
			<!-- 修改学生列表部分 -->
			<view v-for="(student, index) in students" :key="student.userId" class="student-card" :class="{
			    selected: selectedStudents.includes(student.userId),
			    praised: praisedMap[student.userId] && praisedMap[student.userId].subject === currentSubject
			  }">
				<view class="student-info" @click="toggleSelectStudent(student.userId)">
					<image :src="student.aver || '/static/aver1.jpg'" class="avatar"></image>
					<view class="student-details">
						<text class="name">{{student.studentName}}</text>
						<text class="grade">{{student.grade}}</text>
						<!-- 修改已表扬标签，显示具体表扬信息 -->
						<view v-if="praisedMap[student.userId] && praisedMap[student.userId].subject === currentSubject"
							class="praised-badge">
							<uni-icons type="checkmark" size="16" color="#fff"></uni-icons>
							<text>{{praisedMap[student.userId].subjectDetail}}
								<text v-if="praisedMap[student.userId].marks">
									({{praisedMap[student.userId].marks}})
								</text>
							</text>
						</view>
					</view>
					<!-- <uni-icons v-if="!praisedMap[student.userId]" type="checkbox-filled" size="24"
						:color="selectedStudents.includes(student.userId) ? '#4d90fe' : '#ddd'"></uni-icons>
					<uni-icons v-else type="checkmark" size="24" color="#10b981"></uni-icons> -->
				</view>

				<view class="praise-details" v-if="selectedStudents.includes(student.userId)">
					<input v-model="studentPraiseDetails[student.userId]" placeholder="输入具体备注/或分数 (如: 96分)"
						class="detail-input" placeholder-class="detail-placeholder" />
				</view>
			</view>
		</scroll-view>

		<!-- 底部操作按钮 -->
		<view class="action-bar">
			<button class="action-btn cancel" @click="cancelSelection">取消</button>
			<button class="action-btn confirm" @click="confirmPraise">表扬选中学生</button>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';
	export default {
		data() {
			return {
				grade: '二年级',
				students: [],
				selectedStudents: [],
				subjects: [],
				selectedSubject: '语文',
				currentSubject: '语文', // 当前显示的学科
				praiseTitles: ['今日进步较大', '课堂表现优秀', '作业完成出色', '考试成绩优异'],
				selectedPraiseTitle: '今日进步较大',
				newPraiseTitle: '',
				studentPraiseDetails: {},
				praisedStudents: [], // 今日已表扬学生
				praisedMap: {} // 改为在data中定义，而不是计算属性
			}
		},
		computed: {
			filteredPraisedStudents() {
				if (!this.currentSubject) return [];
				return this.praisedStudents.filter(student =>
					student.subject === this.currentSubject
				);
			},
		},
		onLoad(options) {
			uni.getStorage({
				key: "teacher",
				success: (res) => {
					this.teacher = res.data;
				}
			});
			this.grade = options.grade;
			this.fetchStudents(this.grade);
			this.fetchTeacherSubjects();
			this.fetchTodayPraisedStudents();
		},
		methods: {
			fetchTeacherSubjects() {
				uni.showLoading({
					title: '加载中...'
				});
				let that=this;
				// console.log(this.teacher)
				uni.request({
					url: `${globalVariable}/getTeacherSubject?grade=${this.grade}&teacherId=${that.teacher.teacherId}`,
					success: (res) => {
						uni.hideLoading();
						if (res.data.status === 1) {
							// 从返回数据中提取学科列表
							this.subjects = res.data.data.map(item => item.subject);
							// 设置默认选中的学科（第一个）
							if (this.subjects.length > 0) {
								this.selectedSubject = this.subjects[0];
								this.currentSubject = this.subjects[0];
								// 获取已表扬学生
								this.fetchTodayPraisedStudents();
							}
						} else {
							uni.showToast({
								title: res.data.message || '获取学科失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			},
			isStudentPraised(studentId) {
				return this.praisedStudents.some(student => student.studentId == studentId);
			},
			fetchStudents(grade) {
				uni.showLoading({
					title: '加载中...'
				});
				uni.request({
					url: globalVariable + "/getStudentsByGrade?grade=" + grade,
					success: (res) => {
						let info = res.data;
						this.students = info.data;
						this.students.forEach(student => {
							this.$set(this.studentPraiseDetails, student.userId, '');
						});
						uni.hideLoading();
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
					}
				});
			},

			fetchTodayPraisedStudents() {
				let that = this;
				const today = new Date(new Date().getTime() + 8 * 3600 * 1000)
					.toISOString()
					.split('T')[0];

				uni.request({
					url: `${globalVariable}/getPriseByGrade?grade=${that.grade}&createTime=${today}&subject=${that.currentSubject}`,
					method: 'GET',
					success(res) {
						let info = res.data;
						if (info.status === 1) {
							that.praisedStudents = info.data || [];
							// 更新praisedMap
							that.updatePraisedMap();
						}
					},
					fail() {
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						});
					}
				});
			},
			updatePraisedMap() {
				const map = {};
				this.praisedStudents.forEach(item => {
					map[item.studentId] = item;
				});
				this.praisedMap = map;
			},

			changeSubject(e) {
				this.selectedSubject = this.subjects[e.detail.value];
				this.currentSubject = this.selectedSubject;
				this.fetchTodayPraisedStudents(); // 切换学科时重新获取已表扬学生
			},

			addPraiseTitle() {
				if (this.newPraiseTitle.trim()) {
					this.praiseTitles.push(this.newPraiseTitle.trim());
					this.newPraiseTitle = '';
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 300
					});
				}
			},

			removePraiseTitle(index, event) {
				if (event) event.stopPropagation();

				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个表扬主题吗?',
					success: (res) => {
						if (res.confirm) {
							const isRemovingSelected = this.praiseTitles[index] === this.selectedPraiseTitle;
							this.praiseTitles.splice(index, 1);

							if (isRemovingSelected) {
								this.selectedPraiseTitle = this.praiseTitles[0] || '';
							}

							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}
					}
				});
			},

			selectPraiseTitle(title) {
				this.selectedPraiseTitle = title;
			},
			getStudentPraiseDetail(studentId) {
				const praise = this.praisedMap[studentId];
				if (praise) {
					if (praise.marks == "") {
						return `${praise.subjectDetail}`
					}
					return `${praise.subjectDetail} (${praise.marks})`;
				}
				return '';
			},
			toggleSelectStudent(studentId) {
				// 判断当前学科下是否已被表扬
				const isPraised = this.praisedMap[studentId] &&
					this.praisedMap[studentId].subject === this.currentSubject;

				if (isPraised) {
					uni.showToast({
						title: '该学生已被表扬',
						icon: 'none'
					});
					return;
				}

				const index = this.selectedStudents.indexOf(studentId);
				if (index === -1) {
					this.selectedStudents.push(studentId);
				} else {
					this.selectedStudents.splice(index, 1);
				}
			},

			cancelSelection() {
				this.selectedStudents = [];
			},

			confirmPraise() {
				if (this.selectedStudents.length === 0) {
					uni.showToast({
						title: '请选择学生',
						icon: 'none'
					});
					return;
				}

				if (!this.selectedSubject) {
					uni.showToast({
						title: '请选择学科',
						icon: 'none'
					});
					return;
				}

				if (!this.selectedPraiseTitle) {
					uni.showToast({
						title: '请选择表扬主题',
						icon: 'none'
					});
					return;
				}
				let that = this;
				const praises = this.selectedStudents.map(id => {
					const student = this.students.find(s => s.userId === id);

					uni.getStorage({
						key: 'teacher',
						success(res) {
							that.teacher = res.data
						}
					});

					return {
						studentId: id,
						studentName: student.studentName,
						grade: student.grade,
						teacherId: that.teacher.teacherId, // 需要替换为实际教师ID
						teacherName: that.teacher.name, // 需要替换为实际教师姓名
						subject: this.selectedSubject,
						subjectDetail: this.selectedPraiseTitle,
						marks: this.studentPraiseDetails[id] || ''
					};
				});

				uni.showLoading({
					title: '提交中...'
				});
				this.selectedStudents = [];
				uni.request({
					url: globalVariable + "/addPraise",
					method: 'POST',
					data: praises,
					success: (res) => {
						uni.hideLoading();
						if (res.data.status === 1) {
							uni.showToast({
								title: '表扬成功',
								icon: 'success'
							});
							this.selectedStudents = [];
							this.fetchTodayPraisedStudents();
						} else {
							uni.showToast({
								title: res.data.message || '提交失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 背景渐变与毛玻璃效果 */
	.container {
		padding: 20rpx;
		min-height: 100vh;
		background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
		background-image:
			radial-gradient(circle at 10% 20%, rgba(255, 15, 51, 0.3) 0%, transparent 20%),
			radial-gradient(circle at 90% 80%, rgba(8, 255, 111, 0.3) 0%, transparent 20%);
	}

	/* 毛玻璃卡片基础样式 */
	.glass-card {
		background: rgba(255, 255, 255, 0.5);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
		border: 1px solid rgba(255, 255, 255, 0.4);
		transition: all 0.3s ease;
	}

	/* 顶部操作栏 */
	.header-card {
		@extend .glass-card;
		padding: 30rpx;
		margin-bottom: 30rpx;

		.header-content {
			display: flex;
			flex-direction: column;
			gap: 24rpx;
		}
	}

	/* 添加已表扬标签样式 */
	.praised-badge {
		display: inline-flex;
		align-items: center;
		padding: 4rpx 12rpx;
		background: #10b981;
		border-radius: 20rpx;
		font-size: 22rpx;
		color: white;
		margin-top: 8rpx;

		text {
			margin-left: 4rpx;
		}
	}

	/* 修改学生详情部分样式 */
	.student-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;

		.name {
			font-size: 34rpx;
			font-weight: 600;
			color: #1e293b;
		}

		.grade {
			font-size: 24rpx;
			color: #64748b;
		}
	}

	.praise-controls {
		// display: flex;
		gap: 20rpx;
		align-items: center;

		.subject-picker {
			width: 30%;
			margin-bottom: 30rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20rpx 30rpx;
			background: linear-gradient(135deg, #4d90fe 0%, #3a7bd5 100%);
			border-radius: 48rpx;
			min-width: 180rpx;
			box-shadow: 0 4rpx 12rpx rgba(77, 144, 254, 0.3);

			.subject-text {
				font-size: 32rpx;
				font-weight: 500;
				color: white;
				margin-right: 10rpx;
			}
		}

		.praise-input {
			flex: 1;
			display: flex;
			align-items: center;
			background: rgba(255, 255, 255, 0.7);
			border-radius: 48rpx;
			padding: 0 20rpx;
			height: 90rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			.praise-input-field {
				flex: 1;
				height: 100%;
				padding: 0 20rpx;
				font-size: 30rpx;
				color: #333;
			}

			.placeholder {
				color: #aaa;
				font-size: 28rpx;
			}

			.add-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				background: linear-gradient(135deg, #10b981 0%, #059669 100%);
				color: white;
				border-radius: 40rpx;
				padding: 0 30rpx;
				height: 70rpx;
				font-size: 28rpx;
				margin-left: 10rpx;
				box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.3);

				text {
					margin-right: 8rpx;
				}
			}
		}
	}

	/* 表扬主题标签区域 */
	.praise-tags-container {
		width: 100%;
		overflow: hidden;
	}

	.praise-tags-scroll {
		white-space: nowrap;
		width: 100%;
	}

	.praise-tags {
		display: inline-flex;
		gap: 16rpx;
		padding-bottom: 10rpx;
	}

	.praise-tag {
		display: inline-flex;
		align-items: center;
		padding: 18rpx 32rpx;
		background: rgba(255, 255, 255, 0.7);
		border-radius: 48rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: #555;
		transition: all 0.3s ease;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		&.active {
			background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
			color: white;
			box-shadow: 0 4rpx 12rpx rgba(255, 154, 158, 0.3);
		}

		.remove-icon {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 28rpx;
			height: 28rpx;
			margin-left: 10rpx;
			border-radius: 50%;
			background: rgba(0, 0, 0, 0.1);
			color: inherit;
		}
	}

	/* 修改已表扬标签样式 */
	.praised-badge {
		display: inline-flex;
		align-items: center;
		padding: 4rpx 12rpx;
		background: #10b981;
		border-radius: 20rpx;
		font-size: 22rpx;
		color: white;
		margin-top: 8rpx;
		max-width: 80%;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;

		text {
			margin-left: 4rpx;
		}
	}

	/* 已表扬学生卡片样式 */
	.student-card.praised {
		opacity: 0.8;
		background: rgba(16, 185, 129, 0.05);
	}

	/* 隐藏已表扬学生的选择框 */
	.student-card.praised .checkbox {
		display: none;
	}

	/* 已表扬学生标签 */
	.praised-tags {
		@extend .glass-card;
		padding: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;

		.praised-label {
			font-size: 26rpx;
			color: #666;
			margin-right: 16rpx;
			white-space: nowrap;
		}

		.praised-students {
			display: flex;
			flex-wrap: wrap;
			gap: 12rpx;
		}

		.praised-tag {
			padding: 12rpx 20rpx;
			background: rgba(77, 144, 254, 0.15);
			border-radius: 40rpx;
			font-size: 26rpx;
			color: #4d90fe;
			border: 1rpx solid rgba(77, 144, 254, 0.3);
		}
	}

	/* 学生列表 */
	.student-list {
		height: calc(100vh - 380rpx);
		padding-bottom: 140rpx;
	}

	.student-card {
		@extend .glass-card;
		padding: 30rpx;
		margin-bottom: 24rpx;
		animation: fadeIn 0.5s ease forwards;

		&.selected {
			background: rgba(77, 144, 254, 0.15);
			border-color: rgba(77, 144, 254, 0.3);
			box-shadow: 0 8rpx 24rpx rgba(77, 144, 254, 0.1);
		}
	}

	.student-info {
		display: flex;
		align-items: center;
		gap: 24rpx;

		.avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
			border: 2rpx solid rgba(255, 255, 255, 0.6);
		}

		.student-details {
			flex: 1;
			display: flex;
			flex-direction: column;
			gap: 8rpx;

			.name {
				font-size: 34rpx;
				font-weight: 600;
				color: #1e293b;
			}

			.grade {
				font-size: 24rpx;
				color: #64748b;
			}
		}
	}

	.praise-details {
		margin-top: 24rpx;

		.detail-input {
			// width: 100%;
			background: rgba(255, 255, 255, 0.6);
			border-radius: 48rpx;
			padding: 20rpx 30rpx;
			font-size: 28rpx;
			color: #333;
		}

		.detail-placeholder {
			color: #aaa;
			font-size: 26rpx;
		}
	}

	/* 底部操作栏 */
	.action-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		padding: 20rpx;
		background: rgba(255, 255, 255, 0.9);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
		z-index: 10;

		.action-btn {
			flex: 1;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 45rpx;
			font-size: 32rpx;
			font-weight: 500;
			transition: all 0.3s ease;

			&.cancel {
				background: rgba(0, 0, 0, 0.05);
				color: #64748b;
				margin-right: 15rpx;

				&:active {
					background: rgba(0, 0, 0, 0.1);
				}
			}

			&.confirm {
				background: linear-gradient(135deg, #4d90fe 0%, #3a7bd5 100%);
				color: white;
				margin-left: 15rpx;
				box-shadow: 0 4rpx 12rpx rgba(77, 144, 254, 0.3);

				&:active {
					transform: scale(0.98);
				}
			}
		}
	}

	/* 动画效果 */
	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>